package com.station.service.impl;

import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.station.entity.KingErpBillRecord;
import com.station.enums.ErpOrderTypeEnum;
import com.station.param.request.TransferOrder.TransferModelRequsest;
import com.station.service.KingErpBillRecordService;
import com.station.service.TransferOrderDataService;
import com.station.service.mapper.ItemMapper;
import com.station.service.mapper.TransferOrderMapper;
import com.station.service.mapper.UnitMapper;
import com.station.utils.DateUtils;
import com.station.utils.KingDeeUtils;
import com.station.utils.R;
import com.station.utils.StringUtils;
import com.station.vo.ItemVo;
import com.station.vo.ShiftDetail;
import com.station.vo.ShiftOrder;
import com.station.vo.UnitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: dongfangyu
 * @Date: 2025/9/17
 */
@Slf4j
@Service
public class TransferOrderDataServiceImpl implements TransferOrderDataService {
    @Autowired
    private TransferOrderMapper transferOrderMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private KingErpBillRecordService kingErpBillRecordService;

    @Value("${rd.bld.vendorId}")
    private String vendorId;
    @Value("${rd.kingdee.FCustId}")
    private String FCustId;
    @Value("${rd.kingdee.FSalerId}")
    private String FSalerId;
    @Value("${rd.kingdee.transferType}")
    private String transferType;
    /**
     * 分组前缀
     */
    private static final String F_GROUP_PREFIX = "03.13";
    /**
     * 供应商分组
     */
    private static final String F_SUPPLIER_GROUP_PREFIX = "08";

    /**
     * 货主类型
     */
    private static final String BD_OwnerOrg = "BD_OwnerOrg";
    /**
     * 创建组织
     */
    private static final String F_CREATE_ORG_ID = "100";
    /**
     * 顾客业务标识
     */
    private static final String BD_Customer = "BD_Customer";
    /**
     * 往来单位
     */
    private static final String CUST0067 = "CUST0067";

    /**
     * 币别 人民币
     */
    private static final String PRE001 = "PRE001";
    /**
     * 现金结算
     */
    private static final String JSFS01_SYS = "JSFS01_SYS";
    /**
     * 付款单单批量保存业务标识
     */
    private static final String STK_TransferDirect = "STK_TransferDirect";
    /**
     * 调拨类型
     */
    private static final String InnerOrgTransfer = "InnerOrgTransfer";

    private static final String KCZT01_SYS = "KCZT01_SYS";

    private static final String BD_KeeperOrg = "BD_KeeperOrg";

    @Override
    public R batchSyncTransfer(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<ShiftOrder> shiftOrders  = transferOrderMapper.queryOrderList(Long.valueOf(vendorId), startDate, endDate);

        if(shiftOrders!=null && shiftOrders.size()>0){
            for (ShiftOrder shiftOrder : shiftOrders) {
                List<ShiftDetail> shiftDetails = transferOrderMapper.queryOrderDetailList(shiftOrder.getOrderNo());
                shiftOrder.setDetailList(shiftDetails);
            }
            if (!CollectionUtils.isEmpty(shiftOrders)) {
                TransferModelRequsest.Model[] models = new TransferModelRequsest.Model[shiftOrders.size()];
                int index = 0;
                List<KingErpBillRecord> records = new ArrayList<>();
                for (ShiftOrder shiftOrder : shiftOrders) {
                    List<ShiftDetail> shiftDetails = shiftOrder.getDetailList();
                    TransferModelRequsest.FBillEntry[] entities = new TransferModelRequsest.FBillEntry[shiftDetails.size()];
                    int detailIndex = 0;
                    for (ShiftDetail shiftDetail : shiftDetails) {
                        //拼接明细数据
                        UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), shiftDetail.getUnit());
                        String unitCode = "Pcs";
                        if (null != unitVo && null != unitVo.getUnitCode()) {
                            unitCode = unitVo.getUnitCode();
                        }
                        TransferModelRequsest.FBillEntry entity = new TransferModelRequsest.FBillEntry();
                        ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), shiftDetail.getSkuCode());
                        String cartId = null;
                        if (StringUtils.isEmpty(itemVo.getParentCode())) {
                            cartId = itemVo.getCatCode();
                        } else {
                            cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                        }
                        entity.setFMaterialId(new TransferModelRequsest.FNumberObj(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                        entity.setFUnitID(new TransferModelRequsest.FNumberObj(unitCode));
                        entity.setFQty(shiftDetail.getSkuQuantity());
                        entity.setFSrcStockId(new TransferModelRequsest.FNumberObj("bld"+shiftOrder.getOutStoreCode()));// 调出仓库
                        entity.setFSrcStockStatusId(new TransferModelRequsest.FNumberObj(KCZT01_SYS)); //调出库存状态
                        entity.setFDestStockId(new TransferModelRequsest.FNumberObj("bld"+shiftOrder.getInStoreCode()));// 调入仓库
                        entity.setFDestStockStatusId(new TransferModelRequsest.FNumberObj(KCZT01_SYS)); //调入库存状态
                        entity.setFOwnerTypeOutId(BD_OwnerOrg);  //调出货主类型
                        entity.setFOwnerOutId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));  //调出货主
                        entity.setFBusinessDate(DateUtils.format(shiftOrder.getApproveDate()));  //入库日期
                        entity.setFOwnerTypeId(BD_OwnerOrg);  //调入货主类型
                        entity.setFOwnerId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));  //调入货主
                        entity.setFBaseUnitId(new TransferModelRequsest.FNumberObj(unitCode));
                        entity.setFBaseQty(shiftDetail.getSkuQuantity()); //调拨数量（基本单位）
                        entity.setFDestMaterialId(new TransferModelRequsest.FNumberObj(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId())); //调入物料
                        entity.setFKeeperTypeId(BD_KeeperOrg);
                        entity.setFKeeperId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));
                        entity.setFKeeperTypeOutId(BD_KeeperOrg);
                        entity.setFKeeperOutId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));
                        entity.setFSaleUnitId(new TransferModelRequsest.FNumberObj(unitCode)); //销售单位
                        entity.setFSaleQty(shiftDetail.getSkuQuantity());  //销售数量
                        entity.setFSalBaseQty(shiftDetail.getSkuQuantity());  //销售基本数量
                        entity.setFPriceUnitID(new TransferModelRequsest.FNumberObj(unitCode)); //计价单位
                        entity.setFPriceQty(shiftDetail.getSkuQuantity());  //计价数量
                        entity.setFPriceBaseQty(shiftDetail.getSkuQuantity()); //计价基本数量

                        entities[detailIndex++] = entity;
                    }

                    //拼接订单数据
                    TransferModelRequsest.Model model = new TransferModelRequsest.Model();
                    model.setFBillTypeID(new TransferModelRequsest.FNumberObj(transferType));  //单据类型
                    model.setFSaleOrgId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));  //销售组织
                    model.setFSettleOrgId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID)); //结算组织
                    model.setFStockOutOrgId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID)); //调出库存组织
                    model.setFDate(shiftOrder.getApproveDate());
                    model.setFTransferBizType(InnerOrgTransfer);  //调拨类型
                    model.setFBillNo(shiftOrder.getOrderNo());
                    //model.setFBusinessType("2");
                    model.setFOwnerTypeIdHead(BD_OwnerOrg);
                    model.setFOwnerTypeOutIdHead(BD_OwnerOrg);
                    model.setFOwnerOutIdHead(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID)); //调出货主
                    model.setFTransferDirect("GENERAL");
                    model.setFBillEntry(entities);
                    model.setFStockOrgId(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID)); //调入库存组织
                    model.setFOwnerIdHead(new TransferModelRequsest.FNumberObj(F_CREATE_ORG_ID));
                    models[index++] = model;

                    KingErpBillRecord billRecord = KingErpBillRecord.builder().
                            billDate(shiftOrder.getApproveDate()).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_4.getValue().toString())
                            .orderNo(shiftOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(shiftOrder.getOutStoreCode())).isDel(0).build();
                    records.add(billRecord);
                }
                //同步订单数据到金蝶
                TransferModelRequsest purchaseOrderRequest = new TransferModelRequsest();
                purchaseOrderRequest.setModel(models);
                Gson requestGson = new Gson();
                String requestJson = requestGson.toJson(purchaseOrderRequest);
                RepoResult repoResult = KingDeeUtils.batchSave(STK_TransferDirect, requestJson);
                if (repoResult.getResponseStatus().isIsSuccess()) {
                    for (KingErpBillRecord record : records) {
                        record.setStatus(1);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.ok().put("data", repoResult.getResult());
                } else {
                    String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                    for (KingErpBillRecord record : records) {
                        record.setStatus(0);
                        record.setResponText(msg);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.error(msg);
                }
            }else{
                return R.error("未查询到调拨订单数据！");
            }
        } else{
            return R.error("未查询到调拨订单数据！");
        }

    }





}
